import json
import logging
from django.http import JsonResponse
from wxcloudrun.models import salaryList
from wxcloudrun.models import EmpNoVsTel
import requests
logger = logging.getLogger('log')

def login(request, _):
    """
    获取当前计数

     `` request `` 请求对象
    """
    rsp = JsonResponse({'code': 0, 'errorMsg': ''}, json_dumps_params={'ensure_ascii': False})
    try:
        if request.method == 'GET' or request.method == 'get':
            rsp = getEmpNo(request)
        elif request.method == 'POST' or request.method == 'post':
            rsp = getPhone(request)
        else:
            rsp = JsonResponse({'code': -1, 'errorMsg': '请求方式错误'},
                                json_dumps_params={'ensure_ascii': False})
    except Exception as e:
        rsp = JsonResponse({'code': 0, 'errorMsg': str(e)}, json_dumps_params={'ensure_ascii': False})
    logger.info('response result: {}'.format(rsp.content.decode('utf-8')))
    return rsp



def getPhone(request):
    body = request.body
    body = json.loads(str(body, 'utf-8'))
    code=body['code']
    paylod={"code":code}
    url="http://api.weixin.qq.com/wxa/business/getuserphonenumber"
    r=requests.post(url,json=paylod,verify=False)
    phone=r.json()
    r=JsonResponse({'code': 0, 'data': phone},
                 json_dumps_params={'ensure_ascii': False})
    return r


def getEmpNo(request):
    tel = request.GET['tel']
    empno = EmpNoVsTel.objects.values('EmpNo','name').filter(phone=tel).first()
    r = JsonResponse({'code': 0, 'data': empno},
                     json_dumps_params={'ensure_ascii': False})
    return r